﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows;
using System.Windows.Media.Imaging;
using System.IO;

namespace FrontEnd
{
    public static class ControlCaptureHelper
    {
        public static BitmapSource ToImageSource(FrameworkElement obj)
        {
            // Save current canvas transform
            //Transform transform = obj.LayoutTransform;
            //obj.LayoutTransform = null;

            //// fix margin offset as well
            //Thickness margin = obj.Margin;
            //obj.Margin = new Thickness(0, 0, margin.Right - margin.Left, margin.Bottom - margin.Top);

            //// Get the size of canvas
            ////Size size = new Size(obj.Width, obj.Height);
            //Size size = new Size(obj.ActualWidth, obj.ActualHeight);

            //// force control to Update
            //obj.Measure(size);
            //obj.Arrange(new Rect(size));

            RenderTargetBitmap bmp = new RenderTargetBitmap(
                (int)obj.ActualWidth, (int)obj.ActualHeight, 96, 96, PixelFormats.Pbgra32);

            bmp.Render(obj);

            // return values as they were before
            //obj.LayoutTransform = transform;
            //obj.Margin = margin;

            return bmp;
        }

        public static void SaveImageSource(BitmapSource imgSource, BitmapEncoder encoder, Stream stream)
        {
            try
            {
                encoder.Frames.Add(BitmapFrame.Create(imgSource));
                encoder.Save(stream);
            }
            catch (Exception exc)
            {
                MessageBox.Show("Error while saving: " + exc.Message);                
            }
        }
        public static void SaveFrameworkElement(FrameworkElement element, BitmapEncoder encoder, Stream stream)
        {
            SaveImageSource(ToImageSource(element), encoder, stream);
        }
    }
}
